package top.dreamix.njitkit.ui.screen

import android.annotation.SuppressLint
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import cafe.adriel.lyricist.LocalStrings
import top.dreamix.njitkit.data.network.Account
import top.dreamix.njitkit.data.network.NetworkSetting
import top.dreamix.njitkit.data.network.Operator
import top.dreamix.njitkit.ui.theme.NJITKitTheme
import top.dreamix.njitkit.ui.viewmodel.NEW_ACCOUNT_ID
import top.dreamix.njitkit.ui.viewmodel.NetworkConfigUiState
import top.dreamix.njitkit.ui.viewmodel.NetworkConfigViewModel
import java.util.UUID

/**
 * Stateful Composable: Connects to ViewModel and provides data to the stateless UI.
 */
@Composable
fun NetworkConfigScreen(
    navController: NavController,
    vm: NetworkConfigViewModel = viewModel()
) {
    val uiState by vm.uiState.collectAsState()

    NetworkConfigScreenContent(
        navController = navController,
        uiState = uiState,
        onSelectAccount = { vm.selectAccount(it) },
        onSaveAccount = { vm.saveAccount(it) },
        onSaveNetworkSetting = vm::saveNetworkSetting,
        onDeleteAccount = { vm.deleteSelectedAccount() }
    )
}

/**
 * Stateless Composable: Renders the UI based on the provided state and handles user events.
 * This is previewable because it has no dependency on the ViewModel.
 */
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NetworkConfigScreenContent(
    navController: NavController,
    uiState: NetworkConfigUiState,
    onSelectAccount: (String) -> Unit,
    onSaveAccount: (Account) -> Unit,
    onSaveNetworkSetting: (NetworkSetting) -> Unit,
    onDeleteAccount: () -> Unit
) {
    val strings = LocalStrings.current

    Scaffold(
        topBar = {
            TopAppBar(
                colors = TopAppBarDefaults.topAppBarColors(
                    //containerColor = MaterialTheme.colorScheme.primaryContainer,
                    titleContentColor = MaterialTheme.colorScheme.primary,
                ),
                title = { Text(strings.networkConfigTitle) },
                navigationIcon = {
                    IconButton(onClick = { navController.navigateUp() }) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, strings.back)
                    }
                }
            )
        }
    ) { innerPadding ->
        Column(
            modifier = Modifier
                .padding(innerPadding)
                .padding(16.dp)
                .verticalScroll(rememberScrollState()),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
//            Card(modifier = Modifier.fillMaxWidth()) {
//                CurrentStatusSection()
//            }

            Card(modifier = Modifier.fillMaxWidth()) {
                Column(modifier = Modifier.padding(16.dp)) {
                    AccountSelector(uiState = uiState, onAccountSelected = onSelectAccount)
                    Spacer(Modifier.height(16.dp))

                    if (uiState.isLoading) {
                        Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
                            CircularProgressIndicator()
                        }
                    } else {
                        AccountEditor(
                            uiState = uiState,
                            onSave = {
                                onSaveAccount(it);
                                onSaveNetworkSetting(uiState.networkSetting.copy(defaultAccountId = it.id))
                                 },
                            onDelete = onDeleteAccount)
                    }
                }
            }

            Card(modifier = Modifier.fillMaxWidth()) {
                Column(modifier = Modifier.padding(16.dp)) {
                    Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
                        Text(strings.autoLogin, modifier = Modifier.weight(1f))
                        Switch(checked = uiState.networkSetting.autoLogin, onCheckedChange = { onSaveNetworkSetting(uiState.networkSetting.copy(autoLogin = it)) })
                    }
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AccountSelector(
    uiState: NetworkConfigUiState,
    onAccountSelected: (String) -> Unit,
    displayCreateNewAccount: Boolean = true
) {
    val strings = LocalStrings.current
    var expanded by remember { mutableStateOf(false) }
    val selectedDisplayName = if (uiState.isCreateNewMode)
        strings.createNewAccount
    else uiState.selectedAccount?.username ?: ""

    ExposedDropdownMenuBox(
        expanded = expanded,
        onExpandedChange = { expanded = !expanded }
    ) {
        OutlinedTextField(
            value = selectedDisplayName,
            onValueChange = {},
            label = { Text(strings.currentAccount) },
            modifier = Modifier
                .menuAnchor()
                .fillMaxWidth(),
            readOnly = true,
            trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) }
        )
        ExposedDropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false }
        ) {
            if (displayCreateNewAccount) {
                DropdownMenuItem(
                    text = { Text(strings.createNewAccount, color = MaterialTheme.colorScheme.primary) },
                    onClick = {
                        onAccountSelected(NEW_ACCOUNT_ID)
                        expanded = false
                    }
                )
            }

            uiState.allAccounts.forEach { account ->
                DropdownMenuItem(
                    text = { Text(account.username) },
                    onClick = {
                        onAccountSelected(account.id)
                        expanded = false
                    }
                )
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AccountEditor(
    uiState: NetworkConfigUiState,
    onSave: (Account) -> Unit,
    onDelete: () -> Unit,
) {
    val strings = LocalStrings.current
    val isCreateMode = uiState.isCreateNewMode
    val selectedAccount = uiState.selectedAccount

    var username by remember(uiState.selectedAccountId) { mutableStateOf(selectedAccount?.username ?: "") }
    var password by remember(uiState.selectedAccountId) { mutableStateOf(selectedAccount?.password ?: "") }
    var operator by remember(uiState.selectedAccountId) { mutableStateOf(selectedAccount?.operator ?: Operator.CHINA_MOBILE) }
    var tryLoginOffHours by remember(uiState.selectedAccountId) { mutableStateOf(selectedAccount?.tryLoginOffHours ?: false) }

    var operatorExpanded by remember { mutableStateOf(false) }
    val isUsernameValid = username.isNotBlank()

    Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
        OutlinedTextField(
            value = username,
            onValueChange = { username = it },
            label = { Text(strings.username) },
            modifier = Modifier.fillMaxWidth(),
            isError = !isUsernameValid
        )

        ExposedDropdownMenuBox(
            expanded = operatorExpanded,
            onExpandedChange = { operatorExpanded = !operatorExpanded }
        ) {
            OutlinedTextField(
                value = operator.displayName,
                onValueChange = {},
                label = { Text(strings.operator) },
                modifier = Modifier
                    .menuAnchor()
                    .fillMaxWidth(),
                readOnly = true,
                trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = operatorExpanded) }
            )
            ExposedDropdownMenu(expanded = operatorExpanded, onDismissRequest = { operatorExpanded = false }) {
                Operator.values().forEach { selection ->
                    DropdownMenuItem(text = { Text(selection.displayName) }, onClick = {
                        operator = selection
                        operatorExpanded = false
                    })
                }
            }
        }

        OutlinedTextField(
            value = password,
            onValueChange = { password = it },
            label = { Text(strings.password) },
            modifier = Modifier.fillMaxWidth(),
            visualTransformation = PasswordVisualTransformation()
        )

//        Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
//            Text(strings.tryLoginOffHours, modifier = Modifier.weight(1f))
//            Switch(checked = tryLoginOffHours, onCheckedChange = { tryLoginOffHours = it })
//        }

        Spacer(Modifier.height(16.dp))
        Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) {
            AnimatedVisibility(visible = !isCreateMode) {
                OutlinedButton(
                    onClick = { onDelete() },
                    colors = ButtonDefaults.outlinedButtonColors(contentColor = MaterialTheme.colorScheme.error)
                ) {
                    Icon(Icons.Default.Delete, contentDescription = null)
                    Spacer(Modifier.height(4.dp))
                    Text(strings.delete)
                }
            }
            Button(onClick = {
                val accountToSave = Account(
                    id = selectedAccount?.id ?: UUID.randomUUID().toString(),
                    username = username,
                    operator = operator,
                    password = password,
                    tryLoginOffHours = tryLoginOffHours
                )
                onSave(accountToSave)
            }, enabled = isUsernameValid) {
                val buttonText = if (isCreateMode) strings.createAccountButton else strings.saveChangesButton
                Text(buttonText)
            }
        }
    }
}

@Composable
fun CurrentStatusSection() {
    val strings = LocalStrings.current

    Row(
        modifier = Modifier.padding(16.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text("${strings.currentStatus} ", style = MaterialTheme.typography.titleMedium)
        if (false) {
            Text("loggedInAccount.username (loggedInAccount.operator.displayName)", color = MaterialTheme.colorScheme.primary)
        } else {
            Text("unknow", color = MaterialTheme.colorScheme.error)
        }
    }
}

@Preview
@Composable
fun PreviewNetworkConfigScreen() {
    NJITKitTheme {
        val fakeUiState = NetworkConfigUiState(
            allAccounts = listOf(
                Account(id = "1", username = "user1-preview", operator = Operator.CHINA_MOBILE, password = "123"),
                Account(id = "2", username = "user2-preview", operator = Operator.CHINA_TELECOM, password = "abc")
            ),
            selectedAccountId = "1", // Show the first account by default in preview
            isLoading = false,
             networkSetting = NetworkSetting()
        )

        NetworkConfigScreenContent(
            navController = NavController(LocalContext.current),
            uiState = fakeUiState,
            onSelectAccount = {},
            onSaveAccount = {},
            onDeleteAccount = {},
            onSaveNetworkSetting = {}
        )
    }
}
